import axios from 'axios'
import store from '@/store'
import config from '@/config'
import Cookies from 'js-cookie'
// import { Spin } from 'view-design'
import OSS from 'ali-oss'

let client = new OSS({
    region: 'oss-cn-zhangjiakou',
    accessKeyId: 'LTAI4Fm7FCnjThvu6oneb4Uj',
    accessKeySecret: 'UxIMArmlsyXFVeiE2FAijJAxth3kV8',
    bucket: 'mdxundian'
})


let conf = config.conf

// 基本路径
let base = conf.url_prefix

const addErrorLog = errorInfo => {
    const {
        statusText,
        status,
        request: {
            responseURL
        }
    } = errorInfo
    let info = {
        type: 'ajax',
        code: status,
        mes: statusText,
        url: responseURL
    }
    if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
    constructor(baseUrl = baseURL) {
        this.baseUrl = baseUrl
        this.queue = {}
    }
    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            }
        }
        return config
    }
    destroy(url) {
            delete this.queue[url]
            if (!Object.keys(this.queue).length) {
                // Spin.hide()
            }
        }
        // 拦截器
    interceptors(instance, url) {
        // 请求拦截   带上token
        instance.interceptors.request.use(config => {

            if (!Cookies.get('token')) {
                return config
            }
            if (config.method == 'get') {

                config.params.token = Cookies.get('token')
                return config
            }
            config.data.token = Cookies.get('token');
            return config
        }, error => {
            return Promise.reject(error)
        })

        // 响应拦截
        instance.interceptors.response.use(res => {
            return res
        }, err => {
            // 当响应异常时做一些处理
            if (err && err.response) {
                switch (err.response.status) {
                    case 400:
                        err.message = '请求错误(400)';
                        break
                    case 401:
                        err.message = '未授权，请重新登录(401)';
                        break
                    case 403:
                        err.message = '拒绝访问(403)';
                        break
                    case 404:
                        err.message = '请求出错(404)';
                        break
                    case 408:
                        err.message = '请求超时(408)';
                        break
                    case 500:
                        err.message = '服务器错误(500)';
                        break
                    case 501:
                        err.message = '服务未实现(501)';
                        break
                    case 502:
                        err.message = '网络错误(502)';
                        break
                    case 503:
                        err.message = '服务不可用(503)';
                        break
                    case 504:
                        err.message = '网络超时(504)';
                        break
                    case 505:
                        err.message = 'HTTP版本不受支持(505)';
                        break
                    default:
                        err.message = `连接出错(${err.response.status})!`
                }
                console.log(err.message)
            }
            addErrorLog(err.response)
            return Promise.resolve(err)
        })
    }
    request(options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }

    /**
     * ajax post 请求
     * @param {*} url 请求地址
     * @param {*} s_data 请求体
     */
    ajax_post(url, s_data) {
        return this.request({
            method: 'post',
            url: `${base}${url}`,
            data: s_data,
            withCredentials: true,
        })
    }

    /**
     * ajax get 请求
     * @param {*} url 请求地址
     * @param {*} s_data 请求体
     */
    ajax_get(url, params) {
        return this.request({
            method: 'get',
            url: `${base}${url}?`,
            params: params,
            responseType: 'blob',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Access-Token': localStorage.getItem('AccessToken'),
            }
        })
    }

    /**
     *  上传文件到oos
     *
     * @param {*} file
     * @param {*} callback
     * @memberof HttpRequest
     */
    up_to_oos(file, callback) {
        var time = Date.parse(new Date())
        var path = 'console/' + time + '-' + file.name
        client.put(path, file).then(res => {
            if (res.res.status === 200) {
                console.log(res.url);
                callback(res.url)
            } else {
                console.log('文件 ' + path + ' 上传失败，状态码：' + res.res.status)
            }
        })

    }

    // 上传文件请求
    uploadFileRequest(url, params) {

        return this.request({
            method: 'post',
            url: `${base}${url}`,
            data: params,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    }
}
export default HttpRequest